<?php
/**
 * 订单支付记录模型
 */
declare(strict_types=1);

namespace app\model\crm;

use app\model\BaseModel;

class OrderPayment extends BaseModel
{
    protected $name = 'crm_order_payment';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';
    
    // 软删除
    use \think\model\concern\SoftDelete;
    
    // JSON字段
    protected $json = ['payment_proof_files'];
    
    /**
     * 支付项常量
     */
    const ITEM_CONTRACT = 1;  // 合同款
    const ITEM_POST = 2;      // 后期款
    
    /**
     * 支付方式常量
     */
    const METHOD_BANK_TRANSFER = 1;  // 银行转账
    const METHOD_ALIPAY = 2;         // 支付宝
    const METHOD_WECHAT = 3;         // 微信
    const METHOD_CASH = 4;           // 现金
    const METHOD_OTHER = 5;          // 其他
    
    /**
     * 核实状态常量
     */
    const VERIFICATION_PENDING = 0;   // 未核实
    const VERIFICATION_VERIFIED = 1;  // 已核实
    
    /**
     * 关联订单
     */
    public function orderInfo()
    {
        return $this->belongsTo(Order::class, 'order_id', 'id');
    }
    
    /**
     * 关联核实人
     */
    public function verifier()
    {
        return $this->belongsTo(\app\model\admin\User::class, 'verifier_id', 'id');
    }
    
    /**
     * 获取支付项文本
     */
    public function getPaymentItemTextAttr($value, $data): string
    {
        $itemMap = [
            self::ITEM_CONTRACT => '合同款',
            self::ITEM_POST     => '后期款',
        ];
        
        return $itemMap[$data['payment_item']] ?? '未知';
    }
    
    /**
     * 获取支付方式文本
     */
    public function getPaymentMethodTextAttr($value, $data): string
    {
        $methodMap = [
            self::METHOD_BANK_TRANSFER => '银行转账',
            self::METHOD_ALIPAY        => '支付宝',
            self::METHOD_WECHAT        => '微信',
            self::METHOD_CASH          => '现金',
            self::METHOD_OTHER         => '其他',
        ];
        
        return $methodMap[$data['payment_method']] ?? '未知';
    }
    
    /**
     * 获取核实状态文本
     */
    public function getVerificationStatusTextAttr($value, $data): string
    {
        $statusMap = [
            self::VERIFICATION_PENDING  => '未核实',
            self::VERIFICATION_VERIFIED => '已核实',
        ];
        
        return $statusMap[$data['verification_status']] ?? '未知';
    }
    
    /**
     * 核实支付
     */
    public function verify(int $verifierId): bool
    {
        $this->verification_status = self::VERIFICATION_VERIFIED;
        $this->verifier_id = $verifierId;
        $this->verification_time = time();
        
        return $this->save();
    }
}
